package com.example.online_chat.component;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class OnlineUserManager {
    private final Map<Integer, WebSocketSession> sessionMap = new ConcurrentHashMap<>();

    public void online(int userId, WebSocketSession webSocketSession) {
        if (sessionMap.containsKey(userId)) {
            return;
        }
        sessionMap.put(userId, webSocketSession);
        System.out.println("[" + userId + "]  上线!");
    }

    public void offline(int userId, WebSocketSession webSocketSession) {
        if (sessionMap.get(userId) == webSocketSession) {
            return;
        }
        sessionMap.remove(userId);
        System.out.println("[" + userId + "] 下线!");
    }

    public WebSocketSession getSession(int userId) {
        return sessionMap.get(userId);
    }
}
